import { ActionContext, Module } from 'vuex';
import { login, getUserInfo } from '@/api/Login/index'
import type { vuexStore, User } from '@/store/type/interface';
import { ElMessage } from "element-plus"

const state: User = {
  userName: '111111-admin',
  token: '2222',
  menuList: [],
  menuListOld: []
}

const mutations = {
  // 设置用户名信息
  setUserName(state: User,val: string){
    console.log(state)
    console.log(state.userName)
    state.userName = val;
    console.log(state.userName)
    // userModelUse(state)
  },
  // 存储用户token信息
  setToken(state: User,val: string){
    state.token = val;
  },
  // 存储层级过滤后的菜单
  setMenuList(state: User,val: any[]){
    state.menuList = val;
  },
  // 存储初始化的权限菜单
  setMenuListOld(state: User,val: any[]){
    state.menuListOld = val;
  }
}

const actions = {
  // 登陆事件
  async login(ctx: ActionContext<User, vuexStore>){
    const { data } = await login();
    ctx.commit('setUserName', data.userName);
    ctx.commit('setToken', data.token);
    ctx.commit('setMenuListOld', data.menuList);
    
  },

  // 退出登陆事件
  loginOut(ctx: ActionContext<User,{}>){
    ctx.commit('setUserName', '');
    ctx.commit('setToken', '');
    ctx.commit('setMenuListOld', []);
    ctx.commit('setMenuList', []);

    localStorage.clear();
    sessionStorage.clear();
  },

  // 获取用户权限事件
  async getUserInfo(ctx: ActionContext<User,{}>){
    let model = {}
    const { data } = await getUserInfo(model);
    // 根据后端返回的列表渲染路由
    if (!data) {
      ctx.commit('setMenuListOld', []);
      ElMessage.error('当前角色暂无分配菜单')
    }
    if(!data.menuList || data.menuList.length == 0){
      ctx.commit('setMenuListOld', []);
      ElMessage.error('当前角色暂无分配菜单')
    }else{
      // 存储一些基本信息
      localStorage.setItem('userName', data.userName);
      localStorage.setItem('menuList', JSON.stringify(data.menuList));

      // 在vuex中存储一份menuList
      ctx.commit('setMenuListOld', data.menuList);
    }
  }
}


// 定义user数据模型
export const UserModel:Module<User, vuexStore> = {
  state: state,
  mutations: mutations,
  actions: actions
}

// 导出模型方法
type name = keyof typeof mutations
type disPatchName = keyof typeof actions

export const userModelUse = ( store:any )=>{
  return {
    commit: (name:name, data?: any)=>{
      store.commit(name, data)
    },
    dispatch:(name: disPatchName, data?:any)=>{
      store.dispatch(name, data)
    },
    state: store.state.UserModel as User
  }
}